<?php
/**
 * baidu box mp3插件<br/>直接输入歌曲名称和歌手名，自动生成播放器
 *
 * @package BaiduBox MP3插件
 * @author Mr.Asong
 * @version 1.0.3
 * @link http://mrasong.com
 */
class BaiduBox_Plugin implements Typecho_Plugin_Interface{

    /**
     * 激活插件方法,如果激活失败,直接抛出异常
     *
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function activate(){
        /** 后台发布 */
        Typecho_Plugin::factory('admin/write-post.php')->bottom = array('BaiduBox_Plugin', 'render');
        Typecho_Plugin::factory('admin/write-page.php')->bottom = array('BaiduBox_Plugin', 'render');
		
        /** 前台输出 */
        Typecho_Plugin::factory('Widget_Abstract_Contents')->excerptEx = array('BaiduBox_Plugin', 'parse');
        Typecho_Plugin::factory('Widget_Abstract_Contents')->contentEx = array('BaiduBox_Plugin', 'parse');
    }

    /**
     * 添加到后台发布DOM
     */
    public function render(){
		$ids = array(
			'main'  => 'bdbox',
			'text'  => 'text',
			'submit'=> 'btn-submit',
			'adv'   => 'advance-panel'
 		);
		$player = self::getPlayer(
			array(
				'name' => "'+ name + '",
				'artist' => "'+ artist + '",
				'autoplay' => "'+ autoplay + '"
			)
		);
		echo <<<BDBOX_STR
<style type="text/css">
#bdbox_bt_showaddmusic{margin-left:10px;}
#{$ids['main']}{ display:none; }
#bdbox_show_right{ width:196px; }
#bdbox_show_right p.bdbox_show_p_first{ line-height:18px; height:18px; margin:0; }
#bdbox_show_right p.bdbox_show_p_middle{ line-height:18px; height:18px; margin:9px 0; _margin:4px 0; }
#bdbox_show_right p.bdbox_show_p_last{ line-height:22px; height:22px; margin:0; }
#bdbox_in_name, #bdbox_in_artist{ width:190px; border:1px solid #ccc;padding:1px 2px; line-height:18px; font-size:13px; color:#BD6800;font-weight:bold; }
#bdbox_in_autoplay{ width:80px; margin:0; border:1px solid #ccc; padding:0; }
#bdbox_bt_preview, #bdbox_bt_add{ width:50px; height:22px; margin:0; padding:0 2px; _padding:3px 2px; }
#bdbox_bt_preview{ margin:0 4px; }
</style>
<script type="text/javascript">
/**
 * box.baidu.com MP3播放器插件
 * @author Mr.Asong
 * @link http://mrasong.com
 */
var bdbox = {
	id_main: '{$ids['main']}',
	id_text: '{$ids['text']}',
	id_submit: '{$ids['submit']}',
	id_advpanel: '{$ids['adv']}',
	tips:{
		showAddMus: '展开音乐',
		hideAddMus: '收起音乐',
		nameEmpty: '请输入歌曲名称！',
		nameDefault: '歌曲名称',
		nameTit: '输入您要添加的歌曲名称！',
		artistDefault: '歌手名',
		artistTit: '填写歌手名可以使搜索结果更准确！',
		autoplayT: '自动播放',
		autoplayF: '手动播放',
		btView: '预览',
		btAdd: '添加'
	},
	_gid: function(id){ return document.getElementById(id); },
	_val: function(id){ return document.getElementById(id).value ; },
	_html: function(){
		var name = ( this._val('bdbox_in_name')==this.tips.nameDefault ) ? "" : encodeURI( this._val('bdbox_in_name') );
		var artist = ( this._val('bdbox_in_artist') == this.tips.artistDefault ) ? "" : encodeURI( this._val('bdbox_in_artist') );
		var autoplay = this._val('bdbox_in_autoplay')
		var str = '{$player}';
		return str;
	},
	_check: function(){
		if( this._val('bdbox_in_name')==this.tips.nameDefault ){
			alert( this.tips.nameEmpty );
			return false;
		}
		return true;
	},
	_preview: function(){
		if( !this._check() ){ return false; }
		this._gid('bdbox_show').innerHTML = this._html();
	},
	_add: function(){
		if( !this._check() ){ return false; }
		var name = this._val('bdbox_in_name');
		var artist = this._val('bdbox_in_artist');
		var autoplay = this._val('bdbox_in_autoplay');
		var title = "[BaiduMP3]"+ name +" - "+ artist +"[/BaiduMP3]";
		var url = "#BaiduMP3_"+ autoplay +"#";
		if( artist==this.tips.artistDefault ){
			 title = "[BaiduMP3]"+ name +"[/BaiduMP3]"; ;
		}
		insertLinkToEditor( title, url, url );
	},
	init: function(){
		//var str = '<div class="column-18" id="'+ this.id_main +'" style="display:none;">';
		var str = '<div class="column-13" id="bdbox_show"></div>' ;
		str += '<div class="column-05" id="bdbox_show_right"><p class="bdbox_show_p_first">' ;
		str += '  <input type="text" class="text" id="bdbox_in_name" title="'+ this.tips.nameTit +'" ';
		str += '    onblur="this.value=(this.value==\'\') ? this.defaultValue : this.value" ';
		str += '    onfocus="this.value=(this.value==this.defaultValue) ? \'\' : this.value" value="'+ this.tips.nameDefault +'" /></p> ';
		str += '<p class="bdbox_show_p_middle">';
		str += '  <input type="text" class="text" id="bdbox_in_artist" title="'+ this.tips.artistTit +'" ';
		str += '    onblur="this.value=(this.value==\'\') ? this.defaultValue : this.value" ';
		str += '    onfocus="this.value=(this.value==this.defaultValue) ? \'\' : this.value" value="'+ this.tips.artistDefault +'" /></p> ';
		str += '<p class="bdbox_show_p_last"><select id="bdbox_in_autoplay" class="success"> ';
		str += '    <option value="true">'+this.tips.autoplayT+'</option><option value="false" selected="selected">'+this.tips.autoplayF+'</option> ';
		str += '  </select>' ;
		str += '  <input type="button" id="bdbox_bt_preview" class="notice" onmouseover="this.className=\'success\'" onmouseout="this.className=\'notice\'" value="'+ this.tips.btView +'" onclick="bdbox._preview()" /> ';
		str += '  <input type="button" id="bdbox_bt_add" class="notice" onmouseover="this.className=\'success\'" onmouseout="this.className=\'notice\'" value="'+ this.tips.btAdd +'" onclick="bdbox._add()" /> ';
		str += '</p></div>' ;
		//str += '</div>' ;

		var domA = this._gid(this.id_submit).parentNode.parentNode.childNodes;
		for(var i=0; i<domA.length; i++){
			if( domA[i].className=="left" ){
				domA[i].innerHTML += '<span class="media close" id="bdbox_bt_showaddmusic">'+ bdbox.tips.showAddMus +'</span>';
			}
		}
		var domB = this._gid(this.id_advpanel).parentNode;
		var cNode = document.createElement('div');
		cNode.style.display = 'none';
		cNode.className = 'column-18';
		cNode.setAttribute('id', this.id_main);
		cNode.innerHTML = str;
		domB.appendChild(cNode);
		this._gid('bdbox_show').innerHTML = this._html();
		
		(function () {
			window.addEvent('domready', function() {
				$(document).getElement('span.media').addEvent('click', function () {
					Typecho.toggle('#'+bdbox.id_main, $(document).getElement('span.media'),
					bdbox.tips.hideAddMus, bdbox.tips.showAddMus);
				});

			});
		})();	
	}
};
bdbox.init();
</script>	
BDBOX_STR;
    }
	
	/**
	 * 匹配替换处理
	 */
	static function parseCallback($matches){
		$title = $matches[2];
		if( false===stripos(' - ', $title) ){
			$title .= ' - ';
		}
		$song = explode(' - ', $title);
		$player = array(
			'name'   => urlencode($song[0]),
			'artist' => urlencode($song[1]),
			'autoplay' => $matches[1]
		);
		return self::getPlayer($player);
	}
	
    /**
     * 前台显示处理
     */
    public function parse($text, $widget, $lastResult){

        $text = empty($lastResult) ? $text : $lastResult;
        
        if ( $widget instanceof Widget_Archive ) {
            return preg_replace_callback("/\<a[^\>]*#BaiduMP3_(.*?)#[^\>]*\>\[BaiduMP3\](.*?)\[\/BaiduMP3\]\<\/a\>/i", 'BaiduBox_Plugin::parseCallback', $text);
        } else {
            return $text;
        }

    }

	/**
	 * 获取播放器代码
	 */
	public static function getPlayer( $arr=array('name'=>'','artist'=>'','autoplay'=>'false') ){
		return '<embed src="http://box.baidu.com/widget/flash/song.swf?name='. $arr['name'] .'&artist='. $arr['artist'] .'&autoPlay='. $arr['autoplay']
				.'" type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="always" width="500" height="74"></embed>';
	}
    /**
     * 禁用插件方法,如果禁用失败,直接抛出异常
     *
     * @static
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function deactivate(){}

    /**
     * 获取插件配置面板
     *
     * @access public
     * @param Typecho_Widget_Helper_Form $form 配置面板
     * @return void
     */
    public static function config(Typecho_Widget_Helper_Form $form){}
    /**
     * 个人用户的配置面板
     *
     * @access public
     * @param Typecho_Widget_Helper_Form $form
     * @return void
     */
    public static function personalConfig(Typecho_Widget_Helper_Form $form){}

}

